package com.maigao.api.interceptors.identify;

import com.maigao.util.context.Context;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author awei
 * @description:
 * @date 2022/5/15 10:00 下午
 */
public class IdentifyInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private Validator validator;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Identify identify = handlerMethod.getMethodAnnotation(Identify.class);
            final Cookie[] cookies = request.getCookies();
            final boolean validate = validator.validate(identify,
                    request.getParameter("accessKey"),
                    cookies,
                    request.getHeader("Referer"),
                    request.getParameter("csrf"));
            Context context = Context.current();
            if (null != context.getUser()) {
                context.getUser().setBuvid(parserBuvid(request));
            }
            return validate;
        }
        return true;
    }

    private String parserBuvid(HttpServletRequest request) {
        String buvid = request.getHeader("Buvid");
        if (StringUtils.isEmpty(buvid)) {
            buvid = request.getParameter("buvid");
        }
        return buvid;
    }


}